package leetcode_题库;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * Created by IntelliJ IDEA.
 *
 * @ProjectName leetcode
 * @Author Ding
 * @CreateTime 2022/8/26 9:01 星期五
 */
public class _144_二叉树的前序遍历 {

    public static void main(String[] args) {
        TreeNode n1 = new TreeNode(1);
        TreeNode n2 = new TreeNode(2);
        TreeNode n3 = new TreeNode(3);
        TreeNode n4 = new TreeNode(4);
        TreeNode n5 = new TreeNode(5);

        n1.left = n2;
        n1.right = n3;
        n2.left = n4;
        n2.right = n5;

//        List<Integer> nn = preorderTraversal(n1);
        List<Integer> nn = preorderTraversalNoDeep(n1);
        System.err.println(nn);
    }

    /**
     * 解法2：迭代，使用栈的思想，控制栈的元素以控制循环
     *> 2022/08/26 09:31:33
     * 解答成功:
     * 	执行耗时:0 ms,击败了100.00% 的Java用户
     * 	内存消耗:39.4 MB,击败了86.45% 的Java用户
     * @param root
     * @return
     */
    private static List<Integer> preorderTraversalNoDeep(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        //创建栈
        Stack<TreeNode> stack = new Stack<>();
        //创建数组
        List<Integer> arr = new ArrayList<>();
        //初始化栈，存入根结点
        stack.push(root);
        //只要栈不为空，循环持续
        while (!stack.isEmpty()) {
            //弹栈
            TreeNode n = stack.pop();
            //将弹出元素交给arr
            arr.add(n.val);
            //因为栈具有先入后出的特性，因此，要先将右子结点入栈，再处理左子结点，可以保证处理时，是按照左右顺序处理的
            if (n.right != null) {
                //被弹出元素的右子结点不为空，入栈
                stack.push(n.right);
            }
            if (n.left != null) {
                //被弹出元素的左子结点不为空，入栈
                stack.push(n.left);
            }
        }
        return arr;
    }


    /**
     * 解法1：递归（根、左、右）
     * > 2022/08/26 09:13:55
     * 解答成功:
     * 执行耗时:0 ms,击败了100.00% 的Java用户
     * 内存消耗:39.7 MB,击败了48.57% 的Java用户
     *
     * @param root
     * @return
     */
    public static List<Integer> preorderTraversal(TreeNode root) {
        return preorderTraversal(root, new ArrayList<>());
    }

    public static List<Integer> preorderTraversal(TreeNode root, List<Integer> list) {
        if (root == null) {
            return new ArrayList<>();
        }
        list.add(root.val);
        preorderTraversal(root.left, list);
        preorderTraversal(root.right, list);
        return list;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


}
